<?php
/**
 * User: YL
 * Date: 2019/6/10
 */

namespace app\common\controller;

use app\common\ConstAttribute;
use app\common\TraitAttribute;
use restful\traits\CheckData;
use restful\utils\Helper;
use think\App;
use think\Request;

class Base implements ConstAttribute
{
    use TraitAttribute;
    use CheckData;

    /*
     * APP对象
     * @var App
     */
    protected $app;
    /**
     * 请求对象
     * @var Request
     */
    protected $request;
    /**
     * 请求参数
     * @var array
     */
    protected $params;

    public function __construct(App $app)
    {
        $this->app = $app;
        $this->request = $this->app->request;
        $this->params = $this->getRunParams();

        $this->initialize();
    }

    /**
     * 获取应用实例
     * @return App
     */
    public function getApp()
    {
        return $this->app;
    }

    /**
     * 获取请求实例
     * @return Request
     */
    public function getRequest()
    {
        return $this->request;
    }

    /**
     * 获取所有参数值
     * @return array
     */
    public function getParams()
    {
        return $this->params;
    }

    /**
     * 获取参数值
     * @param string $name
     * @param null $value
     * @return mixed
     */
    public function getParam(string $name, $value = null)
    {
        return $this->params[$name] ?? $value;
    }

    /**
     * 获取运行参数
     * @return array
     */
    private function getRunParams()
    {
        return Helper::arrayMapRecursive('trim', $this->request->middleware('runParams', []));
    }
}